<?php

namespace app\job\event;

use app\api\model\settings\DicModel;
use app\api\model\store\Clerk;
use app\common\enum\order\OrderPayStatusEnum;
use app\common\library\sms\Driver as SmsDriver;
use app\common\model\settings\Setting as SettingModel;
use app\common\model\shopper\Shopper;
use GatewayWorker\Lib\Gateway;

/**
 * 订单事件管理
 */
class OverTimeOrderMsg
{
    // 模型
    private $model;

    // 应用id
    private $appId;

    /**
     * 执行函数
     */
    public function handle()
    {
        //定时任务5秒钟执行一次，消息推送30秒推送一次
        $Redis = new \think\cache\driver\Redis(config('cache.stores.redis'));
        $uni_push_time = $Redis->get('uni_push_time');
        if($uni_push_time){
            if($uni_push_time >= 6){
                $uni_push_time = 1;
                $Redis->set('uni_push_time', $uni_push_time+1);
            }else{
                $Redis->set('uni_push_time', $uni_push_time+1);
            }

        }else{
            $uni_push_time = 1;
            $Redis->set('uni_push_time', $uni_push_time);
        }

        if($uni_push_time != 1){
            return;
        }
        try {
            log_write('OverTimeOrderMsg Init : ==========》OverTimeOrderMsg------init----p>>'.$uni_push_time, 'task');
            $model = new \app\common\model\order\Order();
            $now = time();
            $list = $model->where([
                'pay_status' => OrderPayStatusEnum::SUCCESS,
                'delivery_status' => 20,
                'receipt_status' => 10,
                'order_status' => 10,
                'is_over_time_msg' => 0
            ])->select();
//            file_put_contents('client_list.txt',var_export($list ->toArray(),true) . "\r\n", FILE_APPEND);
            $time = DicModel::listAll(['type' => 'sendTime'], [], 'sort_num desc');
            foreach ($list as &$item) {
                $newTimestamp = strtotime('+' . $time[0]['value'] . ' minutes', $item['delivery_time']); // 将当前时间戳加上25分钟
                $newTimestamp = strtotime('-5 minutes', $newTimestamp);
                if ($now >= $newTimestamp) {
//                file_put_contents('client_list22.txt',var_export($item,true) . "\r\n", FILE_APPEND);
                    //订单配送快到时推送消息 (不再发送短信提醒)
                    $this -> pushMsg($item['store_clerk_id']);
//                    $item['is_over_time_msg'] = 1;
                    $item->save();

                    //发短信
//                    $clerk = Clerk::where('clerk_id', '=', $item['store_clerk_id'])->find();
//                    if(!$clerk){
//                        $clerk = (new Shopper()) -> where('id', '=', $item['store_clerk_id'])->find();
//                    }
//                    if (!empty($clerk['mobile'])) {
//                        $smsConfig = SettingModel::getItem('sms', '10001');
//                        $send_template = 'SMS_464470707';
//                        $SmsDriver = new SmsDriver($smsConfig);
//                        $mobile = $clerk['mobile'];
//                        log_write('发送超时手机号' . $clerk['mobile'], 'task');
//                        $send_data = [
//                            'time' => date('Y-m-d H:i:s', $item['delivery_time']),
//                            'order_id' => $item['order_no']
//                        ];
//                        $flag = $SmsDriver->sendSms($mobile, $send_template, $send_data);
//                        if ($flag) {
//                            $item['is_over_time_msg'] = 1;
//                            $item->save();
//                        }
//                    }
                }
            }

        } catch (\Throwable $e) {
            echo 'ERROR ORDER: ' . $e->getMessage() . PHP_EOL;
            log_write('OverTimeOrderMsg TASK : __ ' . $e->getMessage(), 'task');
        }
        return true;
    }

    private function pushMsg($uid)
    {
        Gateway::$registerAddress = '127.0.0.1:1238';
        file_put_contents('client_ids.txt',$uid.'-----'.date('Y-m-d H:i:s') . "\r\n", FILE_APPEND);
        $client_ids = Gateway::getClientIdByUid($uid); //通过uid 获取client_id 返回的是数组;
        file_put_contents('client_ids.txt',var_export($client_ids,true) . "\r\n", FILE_APPEND);
        if(!$client_ids){
            return ;
        }
         $message = '{"type":"time_out","content":"订单还有5分钟超时"}';
        // 向当前client_id发送数据
        foreach ($client_ids as $value){
            Gateway::sendToClient($value, "$message\r\n");
        }
        return;
    }

}
